package com.crux.referes

import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.message.BasicNameValuePair

String baseUrl = "https://dfdev.yonyougov.top";
String adminUser = "9993600";
String adminPassword = "1";
String testUser = "user999";
String testPassword = "1";
long functionId = 3285854038138393608L;

def client = HttpClientBuilder.newInstance().build();

ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES)
        .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//获取token
//String adminToken = getToken(mapper, client, baseUrl, adminUser, adminPassword)
String userToken = getToken(mapper, client, baseUrl, testUser, testPassword)
def agencies = agencyList(mapper, client, baseUrl, userToken, functionId);
println("用户能够看到预算单位数量:${agencies.size()}")


List<Agency> agencyList(ObjectMapper mapper, CloseableHttpClient httpClient, String baseUrl, String token, long functionId) {
    HttpGet httpGet = new HttpGet(baseUrl + "/crux-org/api/agency");
    httpGet.addHeader("Authorization", "Bearer " + token);
    httpGet.addHeader("x-function-id", functionId + "");
    def response = httpClient.execute(httpGet);
    if (response.getStatusLine().getStatusCode() != 200) {
        println("网络错误❌✅")
        return Collections.emptyList();
    }
    return mapper.readValue(response.getEntity().getContent(), new TypeReference<ArrayList<Agency>>() {})
}

String getToken(ObjectMapper mapper, CloseableHttpClient httpClient, String baseUrl, String username, String password) {
    HttpPost post = new HttpPost(baseUrl + "/crux-auth/oauth/token");
    List<BasicNameValuePair> pairs = new ArrayList<>();
    pairs.add(new BasicNameValuePair("username", username));
    pairs.add(new BasicNameValuePair("password", password));
    pairs.add(new BasicNameValuePair("grant_type", "password"));
    pairs.add(new BasicNameValuePair("scope", "read"));
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
    post.setEntity(formEntity);
    post.addHeader("Authorization", "Basic bXlpZDpteXNlY3JldA==");
    CloseableHttpResponse response = httpClient.execute(post);
    JsonNode node = mapper.readTree(response.getEntity().getContent());
    return node.get("access_token").asText();
}

class Agency {
    long id;
    String code;
    String name;
}
